package com.lanhai.utils;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Map;

import com.lanhai.javaBean.AgvBean;
import com.lanhai.javaBean.ControlAreaBean;
import com.lanhai.javaBean.JobBean;
import com.lanhai.model.ControlArea;

import application.MainAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 接收最新的AGV、交管区和任务列表数据
 * @author liangmin
 *
 */
public class UDPListener4Json extends Thread {
	
	private DatagramPacket dp;
	private DatagramSocket ds;
	private MainAction mainAction;
	private int port;
	
	public UDPListener4Json(MainAction mainAction, int port){
		this.mainAction = mainAction;
		this.port = port;
	}
	
	public void run() {
		byte buf[] = new byte[10240];
		dp = new DatagramPacket(buf, buf.length);
		try{
			ds = new DatagramSocket(port);
		}catch(Exception e){
			e.printStackTrace();
		}
		while(true){
			try{
				ds.receive(dp);
			}catch(Exception e){
				e.printStackTrace();
			}
            /******保存数据****/
			try{
	            String receStr = new String(dp.getData(), 0 , dp.getLength(), "UTF-8");
	            //System.out.println("时间:" + DateUtils.getTimeDate(new Date()));
	            JSONObject jo = JSONObject.fromObject(receStr);
	            JSONObject agvMap = jo.getJSONObject("agvMap");
	            if(agvMap != null){
	            	mainAction.main.agvMap = AgvBean.convertJOSNObject(agvMap);
	            	mainAction.fillAgvData();
	            }
	            JSONArray jobArray = jo.getJSONArray("jobList");
	            if(jobArray != null){
	            	mainAction.main.jobList = JobBean.convertJOSNArray(jobArray);
	            	mainAction.refreshJobList();
	            }
	            JSONObject controlAreaMap = jo.getJSONObject("controlAreaMap");
	            if(controlAreaMap != null){
	            	Map<Integer, ControlArea> caMap = ControlAreaBean.convertJOSNObject(controlAreaMap);
	            	if(mainAction.main.controlAreaMap == null){
	            		mainAction.main.controlAreaMap = caMap;
	            	}
	            	mainAction.refreshControlArea(caMap);
	            }
//	            System.out.println("长度：" + receStr.length() + ",内容：" + receStr);
//	            JSONArray jarray = JSONArray.fromObject(receStr);				
			}catch(Exception e){
				e.printStackTrace();
			}
            //mainDeal.receiveDate(jarray);
            //JSONObject json = JSONObject.fromObject(jarray.get(0));
		}	
	}
}
